package com.ewanghuiju.app.ui.home.activity;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ewanghuiju.app.R;
import com.ewanghuiju.app.app.App;
import com.ewanghuiju.app.app.Constants;
import com.ewanghuiju.app.base.BaseActivity;
import com.ewanghuiju.app.base.contract.home.InviteFriendContract;
import com.ewanghuiju.app.model.bean.response.InviteFriendResponBean;
import com.ewanghuiju.app.model.bean.response.RuleBean;
import com.ewanghuiju.app.model.bean.response.UserInfoResponBean;
import com.ewanghuiju.app.model.dp.RealmHelper;
import com.ewanghuiju.app.presenter.home.InviteFriendPresenter;
import com.ewanghuiju.app.test.bean.PintuanHomeBannerBean;
import com.ewanghuiju.app.ui.pintuan.activity.PintuanRuleActivity;
import com.ewanghuiju.app.util.ClipboardUtils;
import com.ewanghuiju.app.util.LoadingDialogUtils;
import com.ewanghuiju.app.util.PermissionUtil;
import com.ewanghuiju.app.util.ShareUtils;
import com.ewanghuiju.app.util.StartActivityUtil;
import com.ewanghuiju.app.util.ToastUtil;
import com.ewanghuiju.app.util.nodoubleclick.AntiShake;
import com.ewanghuiju.app.util.sharemoreimage.Tools;
import com.ewanghuiju.app.util.thread.LoadImageDataThread;
import com.ewanghuiju.app.widget.popupwindow.InviteFriendPopup;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureMediaScannerConnection;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.tools.SdkVersionUtils;
import com.luck.picture.lib.tools.ToastUtils;
import com.muddzdev.styleabletoast.StyleableToast;
import com.stx.xhb.androidx.XBanner;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author sj  qq:751943509
 * @class 邀请好友页面
 * @time 2020/2/19
 */
public class InviteFriendActivity extends BaseActivity<InviteFriendPresenter> implements InviteFriendContract.View {
    @BindView(R.id.xbanner)
    XBanner xbanner;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;

    private List<String> thumbs;

    private int bannerPosition;

    @Override
    protected int getLayout() {
        return R.layout.activity_invite_friend;
    }

    @Override
    protected void initEventAndData() {
        tvTitleRight.setVisibility(View.VISIBLE);
        tvTitleRight.setText(getString(R.string.invite_friend_rule));
        tvTitleRight.setTextColor(ContextCompat.getColor(mContext, R.color.color_999));
        LoadingDialogUtils.show(mContext);
        mPresenter.getData();
    }

    @Override
    protected int getTitleIntText() {
        return R.string.invite_friend_title;
    }

    InviteFriendPopup inviteFriendPopup;

    @OnClick({R.id.tv_now_invite, R.id.tv_title_right})
    public void doClick(View view) {
        if (AntiShake.check(view.getId())) {    //判断是否多次点击
            return;
        }
        switch (view.getId()) {
            case R.id.tv_now_invite:
                if (inviteFriendPopup == null) {
                    inviteFriendPopup = new InviteFriendPopup(mContext, new InviteFriendPopup.ShareItemClickCallback() {
                        @Override
                        public void saveImage() {
                            //保存图片
                            if (thumbs == null || TextUtils.isEmpty(thumbs.get(bannerPosition))) {
                                StyleableToast.makeText(mContext, "未获取到图片", Toast.LENGTH_SHORT, R.style.mytoast).show();
                                return;
                            }

                            PermissionUtil.requestPermissionForActivity(mContext, new PermissionUtil.IPermissionListener() {
                                @Override
                                public void permissionGranted() {
                                    saveNetImageToLoacl(thumbs.get(bannerPosition));
                                }

                                @Override
                                public void permissionDenied() {
                                    ToastUtil.show("权限被拒绝,请设置应用权限");
                                }
                            }, "权限被拒绝,请设置应用权限", PermissionUtil.scan_permissions);
                        }

                        @Override
                        public void wxShare() {
                            //微信分享
                            if (!Tools.isAppAvilible(mContext, "com.tencent.mm")) {
                                StyleableToast.makeText(mContext, "您还没有安装微信", Toast.LENGTH_SHORT, R.style.mytoast).show();
                                return;
                            }
                            toShareImage(SHARE_MEDIA.WEIXIN);
                        }

                        @Override
                        public void friendShare() {
                            if (!Tools.isAppAvilible(mContext, "com.tencent.mm")) {
                                StyleableToast.makeText(mContext, "您还没有安装微信", Toast.LENGTH_SHORT, R.style.mytoast).show();
                                return;
                            }
                            toShareImage(SHARE_MEDIA.WEIXIN_CIRCLE);
                        }

                        @Override
                        public void qqShare() {
                            if (!Tools.isAppAvilible(mContext, "com.tencent.mobileqq")) {
                                StyleableToast.makeText(mContext, "您还没有安装QQ", Toast.LENGTH_SHORT, R.style.mytoast).show();
                                return;
                            }
                            toShareImage(SHARE_MEDIA.QQ);
                        }

                        @Override
                        public void wbShare() {
//                            toShareImage(SHARE_MEDIA.SINA);
                            if (!Tools.isAppAvilible(mContext, "com.tencent.mm")) {
                                StyleableToast.makeText(mContext, "您还没有安装微信", Toast.LENGTH_SHORT, R.style.mytoast).show();
                                return;
                            }
                            RealmHelper realmHelper = App.getAppComponent().realmHelper();
                            UserInfoResponBean userInfoResponBean = realmHelper.getUserInfoResponBean();
                            if (userInfoResponBean == null) {
                                StyleableToast.makeText(mContext, "获取分享信息失败", Toast.LENGTH_SHORT, R.style.mytoast).show();
                                return;
                            }
//                            StyleableToast.makeText(mContext, "请稍后...", Toast.LENGTH_SHORT, R.style.mytoast).show();
                            String shareText = "e网精品福利，惠聚品质生活，让消费者自我产生最大价值，点击→以下链接https://ewanghuijuzhuce.kuaizhan.com?pid=" + userInfoResponBean.getNumber() +
                                    " ，或复制链接至浏览器打开注册，下载e网惠聚，体验更丰富、更有趣的购物体验";
                            ClipboardUtils.copyText(shareText, "内容已复制到粘贴板");
                            ShareUtils.shareText(mContext, SHARE_MEDIA.WEIXIN, shareText, null);
                        }
                    });

                    //弹框执行动画
                    float fromX = 0;
                    float fromY = 1f;
                    float toX = 0;
                    float toY = 0;
                    Animation showAnimation = createTranslateAnimation(fromX, toX, fromY, toY);
                    Animation dismissAnimation = createTranslateAnimation(toX, fromX, toY, fromY);
                    inviteFriendPopup.setShowAnimation(showAnimation);
                    inviteFriendPopup.setDismissAnimation(dismissAnimation);
                    inviteFriendPopup.setPopupGravity(Gravity.BOTTOM);
                }
                inviteFriendPopup.showPopupWindow();
                break;
            case R.id.tv_title_right:
                //拼团规则
                LoadingDialogUtils.show(mContext);
                mPresenter.getPtiguize("2");
                break;
            default:
                break;
        }

    }

    /**
     * 去分享邀请好友
     */
    public void toShareImage(SHARE_MEDIA share_media) {
        if (thumbs == null || TextUtils.isEmpty(thumbs.get(bannerPosition))) {
            StyleableToast.makeText(mContext, "未获取到邀请图片", Toast.LENGTH_SHORT, R.style.mytoast).show();
            return;
        }
        ShareUtils.shareImageNet(mContext, share_media, thumbs.get(bannerPosition), shareListener);
    }

    private UMShareListener shareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            StyleableToast.makeText(mContext, "请稍后...", Toast.LENGTH_SHORT, R.style.mytoast).show();
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {

        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {

        }
    };


    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .titleBar(mToolbar, true)
                .statusBarDarkFont(true)
                .init();
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void showContent(InviteFriendResponBean bean) {
        LoadingDialogUtils.dismissDialog_ios();
        bannerPosition = 0;
        if (bean != null) {
            thumbs = bean.getThumb();
            if (thumbs != null && thumbs.size() > 0) {
                List<PintuanHomeBannerBean> bannerList = new ArrayList<>();
                for (String url : thumbs) {
                    PintuanHomeBannerBean pintuanHomeBannerBean = new PintuanHomeBannerBean();
                    pintuanHomeBannerBean.setImg(url);
                    bannerList.add(pintuanHomeBannerBean);
                }

                xbanner.setBannerData(R.layout.banner_invite_friend, bannerList);
                xbanner.loadImage(new XBanner.XBannerAdapter() {
                    @Override
                    public void loadBanner(XBanner banner, Object model, View view, int position) {
                        ImageView riv = view.findViewById(R.id.banner_image);
//                        ImageLoader.load(mContext, bannerList.get(position).getImg(), riv);
                        Glide.with(mContext).load(bannerList.get(position).getImg()).dontAnimate()
                                .placeholder(R.mipmap.icon_error_picture).error(R.mipmap.icon_error_picture)
                                .diskCacheStrategy(DiskCacheStrategy.NONE)
                                .into(riv);
                    }

                });
                xbanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        bannerPosition = position;
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
            }
        }
    }

    @Override
    public void showMoreContent(String list) {

    }

    @Override
    public void showPtiguize(RuleBean bean) {
        //获取规则成功
        LoadingDialogUtils.dismissDialog_ios();
        if (bean == null) {
            StyleableToast.makeText(mContext, "暂无数据", Toast.LENGTH_SHORT, R.style.mytoast).show();
            return;
        }
        new StartActivityUtil(mContext, PintuanRuleActivity.class)
                .putExtra(Constants.RULE_TITLE, bean.getIntroduce())
                .putExtra(Constants.RULE_CONTENT, bean.getContent())
                .startActivity(true);

    }

    private LoadImageDataThread mLoadDataThread;

    public void saveNetImageToLoacl(String downloadPath) {
        boolean isHttp = PictureMimeType.isHttp(downloadPath);
        LoadingDialogUtils.show(mContext, "保存中");
        if (isHttp) {
            mLoadDataThread = new LoadImageDataThread(downloadPath, mHandler, mContext);
            mLoadDataThread.start();
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constants.SAVE_IMAGE_SUCCESSFUL:
                    try {
                        String path = (String) msg.obj;
                        if (!TextUtils.isEmpty(path)) {
                            if (!SdkVersionUtils.checkedAndroid_Q()) {
                                File file = new File(path);
                                MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), null);
                                new PictureMediaScannerConnection(mContext, file.getAbsolutePath(), () -> {
                                });
                            }
                            StyleableToast.makeText(mContext, "图片保存成功", R.style.mytoast).show();
                        }
                        LoadingDialogUtils.dismissDialog_ios();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case Constants.SAVE_IMAGE_ERROR:
                    ToastUtils.s(mContext, getString(R.string.picture_save_error));
                    LoadingDialogUtils.dismissDialog_ios();
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLoadDataThread != null) {
            mHandler.removeCallbacks(mLoadDataThread);
            mLoadDataThread = null;
        }
    }
}
